package com.woniu108.car.aspect;

import com.woniu108.car.client.PersonClient;
import com.woniu108.carService.commons.log.AdminHistoryLog;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ApiOperationHistoryAspect {

    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private HttpServletRequest request;
    @Resource
    private PersonClient personClient;

    @Around("@annotation(com.woniu108.carService.commons.log.AdminHistoryLog)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 获取请求头中的 token
        String adminId= null;
        try {
            String token = request.getHeader("token");
            String refreshToken=redisUtil.getString(token);
            adminId = JWTUtil.parseAdminToken(refreshToken).get("adminId").toString();
        } catch (Exception e) {
            throw new WoniuException("缺失管理员信息,无法添加操作记录",10002);
        }
        //获取注解方法
        MethodSignature ms= (MethodSignature) pjp.getSignature();
        ApiOperation apiOperation=ms.getMethod().getDeclaredAnnotation(ApiOperation.class);
        String methodName=apiOperation.value();
        //执行储存
        personClient.addAdminHistory(adminId,methodName);
        return pjp.proceed();

    }
}
